package kz.pdt12.hw.framework;

import java.util.List;

import kz.pdt12.hw.data.ContactData;
import kz.pdt12.hw.data.GroupData;
import kz.pdt12.hw.utils.SortedListOf;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateHelper extends HelperBase {

	public HibernateHelper(ApplicationManager manager) {
	  super(manager);
	}

	public SortedListOf<GroupData> listGroups() {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction trans = session.beginTransaction();
		try {
            return new SortedListOf<GroupData>(
              (List<GroupData>) session.createQuery("from GroupData").list());
		} finally {
            trans.commit();
		}
	}

    public SortedListOf<ContactData> listContacts() {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        try {
            return new SortedListOf<ContactData>(
                    (List<ContactData>) session.createQuery("from ContactData").list());
        } finally {
            trans.commit();
        }
    }

    public GroupData getGroup(String id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        try {
            return (GroupData) session.createQuery("from GroupData where id=" + id).list().get(0);
        } finally {
            trans.commit();
        }
    }

    public ContactData getContact(String id) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction trans = session.beginTransaction();
        try {
            Query object = session.createQuery("from ContactData where id=" + id);
            return (ContactData) object.list().get(0);
        } finally {
            trans.commit();
        }
    }
}
